#include "AccountInfo.h"

#include <qbprotocol/include/rdProto.h>
#include <uam/UserAccountManager.h>
#include <widgets/SImageButton.h>

#include <QFont>
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
#include <QPalette>
#include <QPen>
#include <QPixmap>
#include <QPoint>
#include <QScrollBar>
#include <QString>
#include <QStylePainter>
#include <QTimer>
#include <QVBoxLayout>
#include <QWidget>

#include "../StringResource.h"
#include "AccountInfoMenu.h"
#include "auth/MessageProcess.h"
#include "core/ImageMgr.h"
#include "core/StyleMgr.h"

const char kPanelDataBroker[] = "NCD_P.BROKER";  // 经纪商
const char kPanelDataCFETS[] = "CFETS";          // 常用经纪人
const char kPanelDataCDC[] = "CDC";
const char kPanelDataIMSales[] = "IMSALES";  // 一级销售
const char kPanelDataExcel[] = "EXCEL";      // Excel插件

#define MENU_WIDTH 160
#define SPACINT_SIZE 12

enum childid {
  id_panelInfo = 10000,
  id_dataAuthority = 10002,
  id_broker,
  id_cfets,
  id_she,
  id_cze,
  id_cdc,
  id_csi,
  id_firstSell,
  id_excel
};

AccountInfo::AccountInfo(QWidget* parent /*= nullptr*/) : SPopupWindow(parent) {
  setFixedSize(750, 618);
  setTitle(tr("账号信息"));

  setMouseTracking(true);
  m_szInitTag = "";

  QFont m_lfHead = font();
  m_lfHead.setBold(true);
  m_lfHead.setPixelSize(16);
  m_height = 0;
  QFont m_lfContent = font();
  m_lfContent.setBold(true);
  m_lfContent.setPixelSize(12);
  m_Menu.SetFont(m_lfHead, m_lfContent);

  m_crHead = QColor(230, 179, 66);

#if 0  // 后续其他接口接进来，可能会用到
	if (m_szInitTag.length() > 0)
	{
		if (nMenuPos >= 0 && nMenuPos < PanelNum && m_pPanels[nMenuPos]){
			m_Menu.SetSelect(m_pPanels[nMenuPos]->GetID());
		}
	}
#endif
  xQBServicePlatformManagerReq_c req;
  FIELDCOPY(req.m_UserId,
            SSUserAccountManager::instance().GetUserInfo().m_UserId);
  FIELDCOPY(req.m_CompanyId,
            SSUserAccountManager::instance().GetUserInfo().m_CompanyId);

  qb::SSRequestMsg msg;
  msg.m_pRequest = &req;
  msg.m_FuncID = E_FID_QB_SERVICE_PLATFORM_MANAGER_REQ;
  MessagePoster poster(&msg, auth::EncodeFunc);
  poster.send(this);

  m_Rect = rect();
  for (int i = 0; i < PanelNum; i++) {
    m_pPanels[i] = NULL;
  }
  CreateMenus();
}

bool AccountInfo::SetPanelSelect(const QString& sel) {
  // TODO1
  if ((m_panelWidget != nullptr) && !sel.isEmpty()) {
    /*auto children = m_panelWidget->findChildren<QWidget*>();
    for (auto *p : children) {
        log_error("widget named: %s, y=%d",
    p->objectName().toStdString().c_str(), p->y());
    }*/

    QWidget* select =
        m_panelWidget->findChild<QWidget*>(sel, Qt::FindChildrenRecursively);
    if (select) {
      const QPoint p = select->mapTo(m_panelWidget, QPoint{0, 0});
      scrollArea->verticalScrollBar()->setValue(p.y());
      update();

      return true;
    } else {
      log_error("Failed to locate widget named: %s", sel.toStdString().c_str());
    }
  }

  return false;
}

void AccountInfo::resizeEvent(QResizeEvent* event) {
  SPopupWindow::resizeEvent(event);
  Resize();
}

void AccountInfo::showEvent(QShowEvent* event) {
  SPopupWindow::showEvent(event);
  QTimer::singleShot(30, [this]() { emit showup(); });
}

void AccountInfo::Resize() {
  QRect rcClient = rect();

  m_Menu.Resize(rcClient.left() + 8, rcClient.top() + 8, MENU_WIDTH,
                rcClient.height() - 8);
}

void AccountInfo::paintEvent(QPaintEvent* event) {
  QPainter painter(this);

  painter.setRenderHint(QPainter::Antialiasing);
  painter.setBrush(QBrush(StyleMgr::instance().color("ElementBackground")));
  QPen pen1(StyleMgr::instance().color("InnerBorder"), 1);
  painter.setPen(pen1);
  painter.drawRoundedRect(m_Rect, StyleMgr::instance().size("RoundCorner"),
                          StyleMgr::instance().size("RoundCorner"));

  SPopupWindow::paintEvent(event);

  DrawMain();
}
void AccountInfo::DrawMain() {
  QPainter painter(this);
  m_Menu.DrawMenu(&painter);

  QRect r = rect();
  painter.setPen(NAME_COLOR("BorderNormal"));

  int x = 8 + MENU_WIDTH + 12;
  painter.drawLine(QPointF(x, r.top() + 24),
                   QPointF(x, r.top() + r.height() - 8));
}

#if 0  // 后续其他接口进来，可能会用到
void CDlgAccountInfo::InitTag(char* pTag){
	if (!pTag)return;
	m_szInitTag = SSA2W(pTag);
}
#endif

void AccountInfo::SetScroolHeight(int x, int y) {
  int height = 0;

  if (m_Menu.OnLButtonDown(x, y) == id_panelInfo) {
    height = 0;
  }

  int menuPos = m_Menu.OnLButtonDown(x, y) - id_panelInfo;
  if ((menuPos < 0) || (menuPos > PanelNum))
    height = 0;
  else {
    for (int i = 0; i < menuPos - 1; i++) {
      if (m_pPanels[i] == NULL) continue;
      height += m_pPanels[i]->getHeight() + (SPACINT_SIZE + 1);
    }
  }

  scrollArea->verticalScrollBar()->setValue(height);
}

void AccountInfo::mousePressEvent(QMouseEvent* event) {
  SPopupWindow::mouseMoveEvent(event);
  if (event->button() == Qt::LeftButton) {
    if (m_Menu.OnLButtonDown(event->x(), event->y()) >= 0) {
      update();
      // 设置滚动条高度
      SetScroolHeight(event->x(), event->y());

      return;
    }
  }
}

void AccountInfo::onDataArrived(const qb::SSAckMsg& msg) {
  switch (msg.m_FuncID) {
    case E_FID_QB_AUTHORITY_QUERY_NEW_REQ:  // 详情
    case E_FID_QB_CDC_AUTHORITY_REQ_V2:     // 50340,
                                         // //请求中债估值权限，V3.6后替换原50030消息
    case E_FID_QB_CSI_AUTHORITY_REQ:  //= 50265,
                                      ////请求中证估值权限
    {
      Resize();

      update();
      break;
    }
    case E_FID_QB_AUTHORITY_APPLY_REQ:  // 申请
    {
      update();
      break;
    }
    case E_FID_QB_AUTHORITY_APPROVED_PUSH:  // 推送
    {
      xQBAuthorityApplyAckList_c* qList =
          (xQBAuthorityApplyAckList_c*)msg.m_pRet;
      if (qList) {
        CUserAccountInfo& usrInfo =
            SSUserAccountManager::instance().GetUserInfo();
        if (strcmp(qList->m_UserId, usrInfo.m_UserId) == 0) {
          Resize();

          update();
        }
      }
      break;
    }
    case E_FID_QB_USERPERM_APPLY:  // 50281,
                                   // //功能权限申请
    {
      break;
    }
    case E_FID_QB_USERPERM_APPLY_QUERY:  // 50282,
                                         // //功能权限申请状态查询
    {
      xQBUserPermApplyAck_t* pAck = (xQBUserPermApplyAck_t*)msg.m_pRet;
      time_t t = 0;
      if (!pAck) break;
      std::list<xQBUserpermApplyData>::iterator itValid = pAck->m_data.end();
      for (std::list<xQBUserpermApplyData>::iterator it = pAck->m_data.begin();
           it != pAck->m_data.end(); it++) {
        if (strcmp(it->m_functionCode, USER_PERMISSION_NGPC_SALES) == 0 &&
            strcmp(it->m_permValue, "1") == 0) {
          if (it->m_createTime > t) {
            itValid = it;
            t = it->m_createTime;
          }
        }
      }
      if (itValid != pAck->m_data.end()) {
        switch (itValid->m_applyStatus) {
          case 1: {
            SSUserAccountManager::instance().GetPermission().SetStatus(
                *itValid);
            ((CAIPanelDataIMSales*)m_pPanels[PanelDataIMSales])
                ->SetApplyStatus(2);  // 审核中
            break;
          }
          default:
            break;
        }
      }

      update();
      break;
    }
    case E_FID_QB_QMI_EXCHANGE_SCORE_REQ:
    case E_FID_QB_QMI_EXCHANGE_SCORE_PUSH: {
      Resize();

      update();
      break;
    }
    case E_FID_QB_SERVICE_PLATFORM_MANAGER_REQ: {
      xQBServicePlatformManagerAck_c* pData =
          (xQBServicePlatformManagerAck_c*)msg.m_pRet;

      pInfo1->SetServicePlatform(pData);
      update();
      break;
    }
    default:
      break;
  }
}

void AccountInfo::CreateMenus() {
  QString strTemp;
  int heightSum = 0;

  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(1),
                  id_panelInfo);  // 个人资料
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(3),
                  id_dataAuthority);  // 数据权限
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(4), id_broker,
                  id_dataAuthority);  // 经纪商
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(5), id_cfets,
                  id_dataAuthority);  // CFETS
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(6), id_she,
                  id_dataAuthority);  // SHE
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(7), id_cze,
                  id_dataAuthority);  // CZE
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(8), id_cdc,
                  id_dataAuthority);  // 中债
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(9), id_csi,
                  id_dataAuthority);  // 中证
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(10), id_firstSell,
                  id_dataAuthority);  // 一级销售
  m_Menu.InstMenu(NewStringTable::strDlgAccountInfo(11), id_excel,
                  id_dataAuthority);  // Excel插件

  QRect r = rect();

  QVBoxLayout* layout = contentLayout();
  layout->setContentsMargins(MENU_WIDTH + 12 + 2, 0, 0, 0);

  m_panelWidget = new QWidget(this);

  scrollArea = new QScrollArea(this);
  scrollArea->setStyleSheet("background-color:transparent;");
  scrollArea->setWidgetResizable(true);
  scrollArea->setWidget(m_panelWidget);
  scrollArea->setFrameShape(QFrame::NoFrame);
  scrollArea->setFixedHeight(r.bottom() - 1 - 24 - 24);
  layout->addWidget(scrollArea);

  QVBoxLayout* panelLayout = new QVBoxLayout(m_panelWidget);

  pInfo1 = new CAIPanelInfo;
  panelLayout->addWidget(pInfo1);
  pInfo1->Init();
  pInfo1->setFixedHeight(pInfo1->getHeight());
  heightSum += pInfo1->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line = new QPushButton(this);
  line->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line);

  pInfo2 = new CAIPanelDataBroker;
  pInfo2->setObjectName(kPanelDataBroker);
  panelLayout->addWidget(pInfo2);
  pInfo2->setParent(this);
  pInfo2->Init();
  pInfo2->setFixedHeight(pInfo2->getHeight());
  heightSum += pInfo2->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line1 = new QPushButton(this);
  line1->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line1->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line1->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line1);

  pInfo3 = new CAIPanelDataAuthority(CAIPanelDataAuthority::typeCFETS);
  pInfo3->setObjectName(kPanelDataCFETS);
  panelLayout->addWidget(pInfo3);
  pInfo3->Init();
  pInfo3->setFixedHeight(pInfo3->getHeight());
  heightSum += pInfo3->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line2 = new QPushButton(this);
  line2->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line2->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line2->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line2);

  pInfo4 = new CAIPanelDataAuthority(
      CAIPanelDataAuthority::typeSSE);  // pInfo4->setObjectName(???);
  panelLayout->addWidget(pInfo4);
  pInfo4->Init();
  pInfo4->setFixedHeight(pInfo4->getHeight());
  heightSum += pInfo4->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line3 = new QPushButton(this);
  line3->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line3->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line3->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line3);

  pInfo5 = new CAIPanelDataAuthority(
      CAIPanelDataAuthority::typeSZE);  // pInfo5->setObjectName(???);
  panelLayout->addWidget(pInfo5);
  pInfo5->Init();
  pInfo5->setFixedHeight(pInfo5->getHeight());
  heightSum += pInfo5->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line4 = new QPushButton(this);
  line4->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line4->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line4->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line4);

  pInfo6 = new CAIPanelDataCDC;
  pInfo6->setObjectName(kPanelDataCDC);
  panelLayout->addWidget(pInfo6);
  pInfo6->Init();
  pInfo6->setFixedHeight(pInfo6->getHeight());
  heightSum += pInfo6->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line5 = new QPushButton(this);
  line5->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line5->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line5->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line5);

  pInfo7 = new CAIPanelDataCSI;  // pInfo7->setObjectName(???);
  panelLayout->addWidget(pInfo7);
  pInfo7->Init();
  pInfo7->setFixedHeight(pInfo7->getHeight());
  heightSum += pInfo7->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line6 = new QPushButton(this);
  line6->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line6->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line6->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line6);

  pInfo8 = new CAIPanelDataIMSales;
  pInfo8->setObjectName(kPanelDataIMSales);
  panelLayout->addWidget(pInfo8);
  pInfo8->setParent(this);
  pInfo8->Init();
  pInfo8->setFixedHeight(pInfo8->getHeight());
  heightSum += pInfo8->getHeight();

  panelLayout->addSpacing(SPACINT_SIZE);
  QPushButton* line7 = new QPushButton(this);
  line7->setStyleSheet(
      QString("background-color:#%1;")
          .arg(StyleMgr::instance().color("BorderNormal").rgb(), 0, 16));
  line7->setFixedSize(r.width() - MENU_WIDTH - 8 * 2 - 24 * 2, 1);
  line7->setFocusPolicy(Qt::NoFocus);
  panelLayout->addWidget(line7);

  pInfo9 = new CAIPanelDataExcel;
  pInfo9->setObjectName(kPanelDataExcel);
  panelLayout->addWidget(pInfo9);
  pInfo9->Init();
  pInfo9->setFixedHeight(pInfo9->getHeight());
  heightSum += pInfo9->getHeight();

  m_panelWidget->setFixedHeight(heightSum + 200);

  m_pPanels[PanelInfo] = pInfo1;
  m_pPanels[PanelDataBroker] = pInfo2;
  m_pPanels[PanelDataCFETS] = pInfo3;
  m_pPanels[PanelDataSSE] = pInfo4;
  m_pPanels[PanelDataSZE] = pInfo5;
  m_pPanels[PanelDataCDC] = pInfo6;
  m_pPanels[PanelDataCSI] = pInfo7;
  m_pPanels[PanelDataIMSales] = pInfo8;
  m_pPanels[PanelDataExcel] = pInfo9;

  panelLayout->addStretch();
}
